package com.yun.modules.web;

import com.yun.modules.domain.User;
import com.yun.modules.domain.response.OperationResponse;
import com.yun.modules.domain.session.SessionItem;
import com.yun.modules.domain.session.SessionResponse;
import com.yun.modules.repository.UserRepository;
import com.yun.exception.UsernameIsExitedException;
import com.yun.filter.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/v0.1/users")
public class UserController {



    @Autowired
    private UserRepository userRepository;
    @Resource
    private TokenUtil tokenUtil;

    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }

    @RequestMapping(value = "/session", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public SessionResponse newSession(@RequestBody User login, HttpServletRequest request, HttpServletResponse response) {
        User user = userRepository.findByUsername(login.getUsername());
        SessionResponse resp = new SessionResponse();
        SessionItem sessionItem = new SessionItem();
        if (user != null){
            sessionItem.setToken(this.tokenUtil.createTokenForUser(user));
            sessionItem.setUserId(user.getId());
            sessionItem.setFirstName(user.getUsername());
            //sessionItem.setRole(user.getRole());

            resp.setOperationStatus(OperationResponse.ResponseStatusEnum.SUCCESS);
            resp.setOperationMessage("Dummy Login Success");
            resp.setItem(sessionItem);
        }
        else{
            resp.setOperationStatus(OperationResponse.ResponseStatusEnum.ERROR);
            resp.setOperationMessage("Login Failed");
        }
        return resp;
    }


    /**
     * 获取用户列表
     * @return
     */
    @GetMapping("/userList")
    public Map<String, Object> userList(){
        List<User> users = userRepository.findAll();
        Map<String, Object> map = new HashMap<>();
        map.put("users",users);
        return map;
    }

    /**
     * 注册用户 默认开启白名单
     * @param user
     */
    @PostMapping("/signup")
    public User signup(@RequestBody User user) {
        User bizUser = userRepository.findByUsername(user.getUsername());
        if(null != bizUser){
            throw new UsernameIsExitedException("用户已经存在");
        }
        user.setPassword(DigestUtils.md5DigestAsHex((user.getPassword()).getBytes()));
        return userRepository.save(user);
    }

}
